<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;
use App\Org\Developer\Helper;
use App\Http\Controllers\Controller;
// 给密码加密用
use Illuminate\Hashing\BcryptHasher;

/**
 * @author 陈玉琦
 * 后台管理员
 */
class AdminController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.admin.index');
    }

    /**
     * 异步获取列表数据
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function lists(Request $request)
    {
        if ($request->ajax()) {
            $offset = intval($request->get('start'));
            $paginate = Admin::select(['id', 'name', 'username', 'created_at', 'updated_at'])->orderBy('id', 'desc')
                ->paginate(self::PAGE_SIZE, ['*'], 'page', intval($offset / self::PAGE_SIZE) + 1);

            $data = [];
            foreach ($paginate as $item) {
                $data[] = [
                    $item->id,
                    $item->name,
                    $item->username,
                    $item->created_at->toDateTimeString(),
                    $item->updated_at->toDateTimeString(),
                    // '<a type="button" class="btn btn-primary btn-xs">查看</a>',
                    // <a href="' . url('admin/admin/' . $item->id.'/edit') . '" type="button" class="btn btn-primary btn-xs"><i class="fa fa-edit"></i> 编辑</a> <a type="button" class="btn btn-danger btn-xs remove-cate" data-id="'. $item->id .'"><i class="fa fa-remove"></i> 删除</a>
                    '<a href="' . url('admin/admin/' . $item->id.'/edit') . '" type="button" class="btn btn-primary btn-xs"><i class="fa fa-edit"></i> 编辑</a>'
                ];
            }

            $records = [
                'data' => $data,
                'draw' => intval($request->get('draw')),
                'recordsTotal' => $paginate->total(),
                'recordsFiltered' => $paginate->total(),
            ];

            return response()->json($records);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.admin.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, BcryptHasher $hasher)
    {
        $username = $request->input('username');
        $password = $hasher->make($request->input('password'));
        Admin::insert(['username' => $username, 'password' => $password, 'name' => 'hello']);
		return redirect('admin/admin');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return back()->with('status', '管理员 id 不合法.');
        }
        try {
            $updateModel = Admin::select(['id', 'username'])->find($id);
            if (!(isset($updateModel) && $updateModel->username)) {
                return redirect('admin/admin')->with('status', '要修改的管理员不存在.');
            }
            return view('admin.admin.update')->with(['model' => $updateModel]);
        } catch (\Exception $e) {
            return back()->with('status', '管理员修改失败.'. $e->getMessage());
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, BcryptHasher $hasher, $id)
    {
        // $password = $hasher->make($request->input('password'));
        // $model = Admin::find($id);
        // $model->password = $password;
        // $model->save();

        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return back()->with('status', '管理员 id 不合法.');
        }

        try {
            $updateModel = Admin::select(['id', 'username'])->find($id);
            if (!(isset($updateModel) && $updateModel->username)) {
                return redirect('admin/admin')->with('status', '要修改的管理员不存在.');
            }

            // 验证
            $this->validate($request, [
                'password' => 'required|min:6',
            ], [
                'required' => ':attribute 必须.',
                'min' => ':attribute 不能少于 6 位.',
            ]);

            $password = $hasher->make($request->input('password'));
            $updateModel->password = $password;
            $result = $updateModel->save();
            if ($result) {
                return redirect('admin/admin');
            }
            return back()->with('status', '管理员修改失败.');
        } catch (\Exception $e) {
            return back()->with('status', '管理员修改失败.'. $e->getMessage());
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return response()->json(['code' => 200, 'id' => $id]);
    }

    /**
     * 跳转到登录界面
     */
    public function login()
    {
        return redirect(url('admin/login'));
    }
}
